package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseFinishVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    PurchaseDetailService detailService;
    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0 ).or().eq("status",1 );
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void merge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null){// 表明没有这个id
            // 新建
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            baseMapper.insert(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //TODO 确认采购单状态是0或者1才可以合并
        // 进行合并
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(m -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();

            detailEntity.setId(m);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        detailService.updateBatchById(collect);
        // 更新日期
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(finalPurchaseId);
        purchaseEntity.setUpdateTime(new Date());
        baseMapper.updateById(purchaseEntity);
    }

    @Override
    public void received(List<Long> list) {
        // 1当采购单的状态为新建或者已分配，这样才能领取
        List<PurchaseEntity> collect = list.stream().map(id -> {
            PurchaseEntity purchaseEntity = baseMapper.selectById(id);
            return purchaseEntity;
        }).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item ->{
            // 改变状态
            item.setStatus(WareConstant.PurchaseEnum.PURCHASEING.getCode());
            return item;
        }).collect(Collectors.toList());
        // 2领取采购单后，需要修改采购单的状态
        this.updateBatchById(collect);
        // 3 改变采购相的状态
        // TODO
        collect.forEach(item ->{
           List<PurchaseDetailEntity> entities= detailService.listDetailByPurchaseId(item.getId());
           // 更新状态
            List<PurchaseDetailEntity> collect1 = entities.stream().map(entity -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(entity.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailEnum.PURCHASEING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            detailService.updateBatchById(collect1);
        });
    }
    @Transactional
    @Override
    public void done(PurchaseFinishVo doneVo) {
        // 1改变采购单状态
        Long id = doneVo.getId();


        // 2改变采购项的状态 ，获得所有采购项的状态，如果采购项都为采购成功，那么就改变采购单的状态
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        List<PurchaseDetailEntity> updates =new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
           if (item.getStatus() == WareConstant.PurchaseDetailEnum.HASERR.getCode()){
               flag = false;
               detailEntity.setStatus(item.getStatus());
           }else{
               detailEntity.setStatus(WareConstant.PurchaseDetailEnum.FINISH.getCode());
               // 3将成功采购进行入库
               PurchaseDetailEntity byId = detailService.getById(item.getItemId());
               wareSkuService.addStock(byId.getSkuId(), byId.getWareId(), byId.getSkuNum());

           }
           detailEntity.setId(item.getItemId());
           updates.add(detailEntity);
        }
        detailService.updateBatchById(updates);
        // 1改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseDetailEnum.FINISH.getCode():WareConstant.PurchaseDetailEnum.HASERR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        // 3将成功采购进行入库

    }

}